<template>
  <div class="min-h-screen relative flex items-center justify-center p-6 bg-gradient-to-br from-pink-50 via-purple-100 to-yellow-50 overflow-hidden">
    <div class="petals" aria-hidden>
      <span v-for="n in 20" :key="n" class="petal"></span>
    </div>
    <div class="max-w-2xl w-full romatic-card bg-white/80 backdrop-blur-md rounded-3xl p-8 shadow-lg border border-pink-100">
      <div class="text-center mb-6">
        <h1 class="text-5xl font-serif text-pink-600 title">写下你的祝福</h1>
        <p class="mt-2 text-sm text-pink-500 subtitle">给TA一个浪漫的生日惊喜 — 输入姓名、祝福与一个英文/数字自定义码（不可使用中文）</p>
      </div>

      <form @submit.prevent="onSave" class="space-y-4">
        <div>
          <label class="text-sm text-gray-600">自定义码（仅英文/数字/-_，用于生成分享链接）</label>
          <input v-model="key" required placeholder="例如: alice2025" class="mt-1 w-full px-4 py-3 rounded-xl border focus:ring-2 focus:ring-pink-200" />
          <p v-if="keyError" class="text-red-500 text-sm mt-1">{{ keyError }}</p>
        </div>

        <div>
          <label class="text-sm text-gray-600">过生日人的姓名</label>
          <input v-model="name" required placeholder="TA 的名字" class="mt-1 w-full px-4 py-3 rounded-xl border focus:ring-2 focus:ring-pink-200" />
        </div>

        <div>
          <label class="text-sm text-gray-600">你的祝福</label>
          <textarea v-model="message" required rows="4" placeholder="写下你的祝福，让 TA 感到被爱" class="mt-1 w-full px-4 py-3 rounded-xl border focus:ring-2 focus:ring-pink-200"></textarea>
        </div>

        <div>
          <label class="text-sm text-gray-600">上传一张图片（可选，最大 1MB）</label>
          <input type="file" accept="image/*" @change="onFileChange" class="mt-2" />
          <p v-if="imageError" class="text-red-500 text-sm mt-1">{{ imageError }}</p>
          <div v-if="imageData" class="mt-3">
            <div class="text-sm text-gray-500">图片预览：</div>
            <img :src="imageData" alt="preview" class="mt-2 rounded-lg max-h-48 object-contain border" />
          </div>
        </div>

        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">自动过期：7 天（可在服务器调整）</div>
          <div class="flex gap-3">
            <button type="button" @click="onPreview" class="px-4 py-2 rounded-full bg-pink-100 text-pink-700">预览</button>
            <button type="submit" class="px-5 py-2 rounded-full bg-pink-600 text-white shadow">保存并生成链接</button>
          </div>
        </div>
      </form>

      <div v-if="saving" class="mt-4 text-center text-gray-600">正在保存…</div>
      <div v-if="result" class="mt-4 bg-pink-50 p-3 rounded-lg">
        <div class="text-sm">已保存： <a :href="shareUrl" class="text-pink-600 underline">点击查看 / 复制链接分享</a></div>
        <div class="mt-2"><button @click="copyLink" class="px-3 py-1 bg-pink-600 text-white rounded">复制链接</button></div>
      </div>

      <p class="mt-6 text-xs text-gray-400">提示：自定义码不能包含中文字符。分享链接示例：<span class="font-mono">/live-tools/birthday/yourkey</span></p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const key = ref('')
const name = ref('')
const message = ref('')
const saving = ref(false)
const result = ref(null)
const imageData = ref(null)
const imageError = ref('')

const router = useRouter()

const keyError = computed(() => {
  if (!key.value) return ''
  // reject Chinese unified ideographs
  if (/[\u4e00-\u9fff]/.test(key.value)) return '自定义码不能包含中文'
  if (/[^\w\-]/.test(key.value)) return '仅允许字母、数字、下划线或连字符'
  if (key.value.length > 80) return '自定义码太长'
  return ''
})

const shareUrl = computed(() => result.value ? `${window.location.origin}/live-tools/birthday/${encodeURIComponent(key.value)}` : '')

function onPreview() {
  // quick client-side preview using a route with ephemeral state
  const k = key.value || 'preview'
  // keep preview conservative: navigate and rely on query for name/message; image preview is shown locally in form
  router.push({ path: `/live-tools/birthday/${encodeURIComponent(k)}`, query: { preview: '1', name: name.value, message: message.value } })
}

function onFileChange(e) {
  imageError.value = ''
  const f = (e.target && e.target.files && e.target.files[0]) || null
  if (!f) { imageData.value = null; return }
  if (!f.type.startsWith('image/')) { imageError.value = '请选择图片文件' ; return }
  const maxBytes = 1 * 1024 * 1024
  if (f.size > maxBytes) { imageError.value = '图片大小不能超过 1MB'; return }
  const reader = new FileReader()
  reader.onload = () => { imageData.value = String(reader.result) }
  reader.onerror = () => { imageError.value = '无法读取文件' }
  reader.readAsDataURL(f)
}

async function onSave() {
  if (keyError.value) return alert(keyError.value)
  if (!key.value || !name.value || !message.value) return alert('请完整填写')
  saving.value = true
  try {
    const res = await fetch('/api/live/birthday.save', {
      method: 'POST', headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ key: key.value, name: name.value, message: message.value, imageBase64: imageData.value })
    })
    const data = await res.json()
    if (res.ok && data?.status === 'ok') {
      result.value = data
      // navigate to display page
      window.location.href = `/live-tools/birthday/${encodeURIComponent(key.value)}`
    } else {
      alert(data?.message || '保存失败')
    }
  } catch (e) {
    alert('保存失败: ' + e)
  } finally {
    saving.value = false
  }
}

function copyLink() {
  if (!shareUrl.value) return
  navigator.clipboard?.writeText(shareUrl.value)
    .then(() => alert('链接已复制'))
    .catch(() => alert('复制失败'))
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

:root{
  --pink-600: #d63384;
}

.romatic-card{
  transition: transform .6s cubic-bezier(.2,.9,.2,1), box-shadow .4s;
  transform: translateY(0);
}
.romatic-card:hover{ transform: translateY(-6px); box-shadow: 0 30px 50px rgba(217,70,130,0.12) }

.title{ font-family: 'Playfair Display', serif; letter-spacing: 0.6px }
.subtitle{ font-family: 'Poppins', sans-serif }

/* petals */
.petals{ position:absolute; inset:0; pointer-events:none; overflow:hidden }
.petal{ position:absolute; top:-10%; left:50%; width:14px; height:22px; background:linear-gradient(180deg,#fff0f6,#ffd6e7); border-radius:50% 50% 40% 60%; opacity:.9; transform-origin:center; animation:fall 8s linear infinite; box-shadow: 0 2px 6px rgba(0,0,0,0.06) }
.petal:nth-child(odd){ width:12px; height:18px; background: linear-gradient(180deg,#ffeef8,#ffd5e9); }
.petal:nth-child(2n){ animation-duration:9s; animation-delay: -2s }
.petal:nth-child(3n){ animation-duration:7s; animation-delay: -4s }
.petal:nth-child(4n){ animation-duration:10s; animation-delay: -6s }

@keyframes fall{
  0%{ transform: translate3d(0,-10vh,0) rotate(0deg); opacity:0 }
  10%{ opacity:1 }
  50%{ transform: translate3d(-20vw,40vh,0) rotate(90deg) }
  75%{ transform: translate3d(10vw,70vh,0) rotate(160deg); opacity:.9 }
  100%{ transform: translate3d(-10vw,110vh,0) rotate(220deg); opacity:0 }
}

/* add slight heart background in corner */
.romatic-card::before{
  content:''; position:absolute; inset:auto -40px -40px auto; width:160px; height:160px; background: radial-gradient(circle at 30% 30%, rgba(255,182,193,0.25), transparent 40%); transform: rotate(20deg); border-radius:50%; pointer-events:none
}

</style>
